package com.iflytek.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.github.pagehelper.PageInfo;
import com.iflytek.dto.CouponDTO;
import com.iflytek.entity.Coupon;
import com.iflytek.service.CouponService;
import lombok.extern.java.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@Log
public class CouponController {

    @Autowired
    private CouponService couponService;

    @GetMapping("/coupon")
    public String coupon(@ModelAttribute(value = "params") Coupon params, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "15") Integer pageSize, Model model) {
        PageInfo pageInfo = couponService.findByParams(params, pageNum, pageSize);
        model.addAttribute("pageInfo", pageInfo);
        return "coupon";
    }
    @ResponseBody
    @GetMapping("/couponAjax")
    public Object couponAjax(@ModelAttribute(value = "params") Coupon params, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "15") Integer pageSize, Model model) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        PageInfo pageInfo = couponService.findByParams(params, pageNum, pageSize);
        List<Coupon> list = pageInfo.getList();
        System.out.println(list);
        return list;
    }


    @GetMapping("/upload")
    public String uploadCoupon() {
        return "upload";
    }

    @PostMapping("/upload")
    public String saveUpload(MultipartFile fileName, Model model) {

        //读取信息
        try {
            EasyExcel.read(fileName.getInputStream(), CouponDTO.class, new ReadListener() {
                @Override
                public void invoke(Object o, AnalysisContext analysisContext) {
                    CouponDTO couponDTO = (CouponDTO) o;
                    Coupon coupon = new Coupon();
                    BeanUtils.copyProperties(couponDTO, coupon);
                    coupon.setPromotePrice(couponDTO.getPrice() - couponDTO.getCouponValue());
                    coupon.setSellerId(couponDTO.getSellerShop());
                    couponService.save(coupon);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {

                }
            }).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
        model.addAttribute("msg", "上传成功");
        return "upload";
    }
}
